<?php

namespace EthanZ\LaravelExt\Redis;

use Illuminate\Support\Facades\Redis;
use Illuminate\Redis\Connections\Connection;

class BaseRedis
{


    /**
     * @var string
     */
    protected string $appName;


    /**
     * 缓存名
     *
     * @var string
     */
    protected string $key;


    /**
     * 超时时间
     *
     * @var int
     */
    protected int $timeout;


    /**
     * @var Connection
     */
    protected Connection $redis;


    public function __construct()
    {
        $this->appName = 'bas';
        $this->redis   = Redis::connection();
    }


    /**
     * 实例
     *
     * @return static
     */
    public static function query(): static
    {
        return (new static());
    }


    /**
     * 设置缓存名
     *
     * @param array  $keyData
     * @param string $suffix
     *
     * @return BaseRedis
     */
    public function setKey(array $keyData, string $suffix = ''): static
    {
        $this->key     = $this->appName . ':' . $keyData[0];
        $this->timeout = $this->timeout ?? ($keyData[1] ?? 0);
        if ($suffix) {
            $this->key .= ':' . $suffix;
        }

        return $this;
    }


    /**
     * 设置超时时间
     *
     * @param int $timeout
     *
     * @return $this
     */
    public function setTimeout(int $timeout): static
    {
        $this->timeout = $timeout;

        return $this;
    }


    /**
     * 获取缓存名
     *
     * @return string
     */
    public function getKey(): string
    {
        return $this->key;
    }


    /**
     * 获取缓存
     *
     * @return mixed
     */
    public function get(): mixed
    {
        return json_decode($this->redis->get($this->key), true);
    }


    /**
     * 设置缓存
     *
     * @param mixed $value
     */
    public function set(mixed $value): void
    {
        $this->redis->set($this->key, json_encode($value, 256), 'ex', $this->timeout);
    }


    /**
     * 锁
     *
     * @return mixed
     */
    public function lock(): mixed
    {
        return $this->redis->set($this->key, 1, 'ex', $this->timeout, 'nx');
    }


    /**
     * 解锁
     *
     * @return int
     */
    public function unLock(): int
    {
        return $this->redis->set($this->key, null);
    }
}
